package com.lw.security.security.handler;

import com.lw.security.mapper.RoleMapper;
import com.lw.security.pojo.Menu;
import com.lw.security.pojo.Role;
import com.lw.security.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/28 23:42
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RoleMapper roleMapper;

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    /**
     * 当认证成功的时候
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //super.onAuthenticationSuccess(request, response, authentication);
        //response.sendRedirect("/success.html");
        response.getWriter().write("denglu chenggong");

        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        //获取用户权限
        List<Role> roleList = roleMapper.findByUserIdAndMenu(baseUser.getUserId());
        Set<String> allPermission=new HashSet<>();
        roleList.forEach(role -> {
            List<Menu> menuList = role.getMenuList();
            List<String> permissionList = menuList.stream().map(Menu::getPermission).collect(Collectors.toList());
            allPermission.addAll(permissionList);
        });

        //更新用户的权限,讲用户权限的字符串转换为security中的权限对象
        List<SimpleGrantedAuthority> authorityList = allPermission.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //刷新用户的权限
        //参数1 用户
        //参数2 用户密码
        //参数3 权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser,authentication.getCredentials(),authorityList));
    }
}
